#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    if(!db.isValid())
    {
        QMessageBox::critical(this,"错误提示","数据库驱动加载失败");
        throw std::runtime_error("数据库驱动加载失败");
    }
    db.setDatabaseName("..\\..\\testDB.db");
    if(!db.open())
    {
        QMessageBox::critical(this,"错误提示","数据库打开失败");
        throw std::runtime_error("数据库打开失败");
    }

    QSqlQueryModel* model = new QSqlQueryModel;
    model->setQuery("SELECT * FROM employee;");

    QTableView* tv_sqlite = new QTableView(this);
    tv_sqlite->setModel(model);

    QVBoxLayout* vBoxLayout1 = new QVBoxLayout;
    vBoxLayout1->addWidget(tv_sqlite);
    // ui->centralwidget->setLayout(vBoxLayout1);
    this->centralWidget()->setLayout(vBoxLayout1);

#if 0
    QSqlRecord rec = model->record(1);
    qDebug() << rec.value(0).toString() << rec.value(1).toString();
    for(int i=0;i<rec.count();i++)
    {
        qDebug() << rec.value(i).toString();
    }
#endif

    QSqlQuery myQuery("SELECT * FROM employee;");
    if(!myQuery.exec())
    {
        qDebug() << myQuery.lastError().text();
        throw std::runtime_error("sql的查询语句执行失败!");
    }

    QSqlRecord rec = myQuery.record();
    qDebug() << "sqlRecord字段的个数:" << rec.count();
    for(int i=0;i<rec.count();i++)
    {
        qDebug() << rec.value(i).typeName() << rec.field(i).name();
    }

    while(myQuery.next())
    {
        qDebug() << myQuery.value(0).toInt() << "\t"
                 << myQuery.value(1).toString() << "\t"
                 << myQuery.value(2).toInt() << "\t"
                 << myQuery.value(3).toString() << "\t"
                 << myQuery.value(4).toString() << "\t"
                 << myQuery.value(5).toDouble() << "\t"
                 << myQuery.value(6).toString() << "\t";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
